import Taro from '@tarojs/taro';
import React, { memo } from "react";
import { View } from '@tarojs/components';
import { Toast, Uploader } from "@antmjs/vantui";
import apiConfig from '@/services/apiConfig'

interface PdsUpLoaderImageProps {
    maxCount: number;//限制数量
    url: string;
    imageurl?: string;
    // imageId?:string;
    disabled: boolean;
    onUpload?: Function;
    onDelete?: Function;
}


class PdsUpLoaderImage extends React.Component<PdsUpLoaderImageProps, any> {
    constructor(props: PdsUpLoaderImageProps) {
        super(props);
        this.state = { value: [] };
    }

    static defaultProps = {
        maxCount: 1,
        url: 'file/upload/file',
        imageurl: '',
        disabled: false,
        onChange: () => {
        }
    }

    componentDidUpdate(prevProps) {
       
    }

    componentWillMount() {
        if (this.props.imageurl != null && this.props.imageurl.length > 0) {
            // 当某个特定的prop值发生变化时执行逻辑
            console.log('Prop value has changed:', this.props.imageurl);
            let authToken = Taro.getStorageSync('auth-token') || ''//拿到本地缓存中存的token
            let orgTag = apiConfig.orgTag//拿到本地缓存中存的token
            var header = {
              'auth-token': authToken, //将token添加到头部
              'org-tag': orgTag
            }
        
            Taro.downloadFile({
                url: this.props.imageurl,
                header: header,
                success: (res) => {
                  if (res.statusCode === 200) {
                    const filePath = res.tempFilePath;
                    console.log(filePath);
                    Taro.saveFile({
                      tempFilePath: filePath,
                      success: (result) => {
                        const savedFilePath = result.savedFilePath;
                        console.log(savedFilePath);
                        this.setState({ value:[
                            {
                              url: savedFilePath,
                              name: '图片',
                            },] })
                      },
                    });
                  }
                },
                fail: (err) => {
                  console.log('失败', err);
                },
              });


            // Taro.request({
            //     this.props.imageurl,
            //     header,
            //     responseType: 'arraybuffer',
            //     success: (res) => {
            //       const base64 = Taro.arrayBufferToBase64(res.data);
            //     //   setImageUrl(`data:image/jpeg;base64,${base64}`);
            //     },
            //     fail: (err) => {
            //       console.error('Image load failed:', err);
            //     },
            //   });
            // this.setState({ value: { url: this.props.imageurl } })
        }
    }

    afterRead = (event) => {
        const { file } = event.detail
        const { value } = this.state;
        const { url, onUpload } = this.props;
        // 可在此处新增云上传图片操作
        this.setState({ value: value.concat(file) })

        let authToken = Taro.getStorageSync('auth-token') || ''//拿到本地缓存中存的token
        let orgTag = apiConfig.orgTag//

        var header = {
            'auth-token': authToken, //将token添加到头部
            'org-tag': orgTag
        }
        var timestamp = (new Date()).valueOf();//获取当前毫秒的时间戳，准确！

        Taro.uploadFile({
            url: apiConfig.baseUrl + '/api/v1/' + url,
            filePath: file.url,
            header: header,
            name: 'upload_file',
            fileName: timestamp + '.jpg',
            success(result) {
                let data = {};
                try {
                    data = JSON.parse(result.data);
                    if (onUpload) {
                        onUpload(timestamp + '.jpg', data['data']);
                    }
                } catch (error) {
                    data = {};
                }
                console.log(data);
                

            },
            fail() {
                Toast.fail('请上传 JPG/JPEG/PNG 格式图片')
                // showToast(toastId, 'fail', '请上传 JPG/JPEG/PNG 格式图片');
            }
        });
    }

    deleteAction = (event) => {
        const { index } = event.detail
        const { value } = this.state;
        const { onDelete } = this.props;
        const valueNew = JSON.parse(JSON.stringify(value))
        valueNew.splice(index, 1)
        this.setState({ value: valueNew })
        console.log(value)
        if (onDelete) {
            onDelete(value);
        }
    }

    render() {
        const { value } = this.state;
        const { disabled, maxCount } = this.props;
        return (
            <View className="uploader-view">
                <Uploader disabled={disabled}
                    accept="image"
                    fileList={value}
                    onAfterRead={this.afterRead.bind(this)}
                    onDelete={this.deleteAction.bind(this)}
                    deletable={!disabled}
                    maxCount={maxCount}
                />
                <Toast />
            </View>

        );
    }
}


export default memo(PdsUpLoaderImage);